package com.zksk.admin.service.org.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksk.admin.mapper.org.OrgDao;
import com.zksk.admin.service.org.OrgService;
import com.zksk.common.core.constant.OrgConstants;
import com.zksk.common.core.domain.R;
import com.zksk.common.core.exception.ServiceException;
import com.zksk.common.core.utils.SpringUtils;
import com.zksk.common.core.utils.StringUtils;
import com.zksk.common.security.utils.SecurityUtils;
import com.zksk.common.security.utils.SeqCodeUtils;
import com.zksk.mbg.admin.domain.Org;
import com.zksk.mbg.admin.domain.OrgProduct;
import com.zksk.mbg.admin.mapper.OrgMapper;
import com.zksk.mbg.admin.mapper.OrgProductMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 机构（银行、担保、保险）表 服务实现类
 * </p>
 *
 * @author Zksk Acmen
 * @since 2022-12-01
 */
@Service
public class OrgServiceImpl extends ServiceImpl<OrgMapper, Org> implements OrgService {

    @Autowired
    private OrgDao orgDao;

    @Autowired
    private OrgMapper orgMapper;

    @Autowired
    private OrgProductMapper orgProductMapper;


    @Override
    public Boolean checkOrgCodeKeyUnique(String orgCode) {
        if(StringUtils.isNull(orgCode)){
            return OrgConstants.NOT_UNIQUE_FALSE;
        }else{
            Long aLong = orgMapper.selectCount(new QueryWrapper<Org>().eq(Org.ORG_CODE, orgCode));
            if (aLong > 0){
                return OrgConstants.NOT_UNIQUE_FALSE;
            }else{
                return OrgConstants.UNIQUE_TRUE;
            }
        }
    }

    @Override
    public Boolean checkOrgNameUnique(String orgName) {
        if(StringUtils.isNull(orgName)){
            return OrgConstants.UNIQUE_TRUE;
        }else{
            Long aLong = orgMapper.selectCount(new QueryWrapper<Org>().eq(Org.ORG_NAME, orgName));
            if (aLong > 0){
                return OrgConstants.NOT_UNIQUE_FALSE;
            }else{
                return OrgConstants.UNIQUE_TRUE;
            }
        }
    }

    @Override
    public Boolean checkOrgContactTellUnique(String contactTell) {
        if (StringUtils.isNull(contactTell)) {
            return OrgConstants.UNIQUE_TRUE;
        } else {
            Long aLong = orgMapper.selectCount(new QueryWrapper<Org>().eq(Org.CONTACT_TELL, contactTell));
            if (aLong > 0) {
                return OrgConstants.NOT_UNIQUE_FALSE;
            } else {
                return OrgConstants.UNIQUE_TRUE;
            }
        }
    }

    @Override
    @Transactional
    public Org saveOrg(Org org, List<Long> orgProductIds) {
        String createByName = SecurityUtils.getUsername();

        Long insertOrgId = null;
        if(org.getOrgId() != null){
            // 1、如果机构id已经存在
            insertOrgId = org.getOrgId();
            org.setUpdateBy(createByName);
            // 对机构信息做变更
            orgMapper.updateById(org);  // 更新
        }else{
            // 2、如果机构id不存在
            String geneOrgCode = geneOrgCode(org.getOrgType());
            org.setOrgCode(geneOrgCode);// 插入机构编码
            org.setCreateBy(createByName);
            orgMapper.insert(org);  // 新增
            insertOrgId = org.getOrgId();
        }

        if(orgProductIds != null && orgProductIds.size() > 0){
            // 查询机构产品id是否全部都有
            List<OrgProduct> orgProducts = orgProductMapper.selectBatchIds(orgProductIds);
            if(orgProducts != null){
                List<Long> collect = orgProducts.stream().map(OrgProduct::getId).collect(Collectors.toList());
                orgProductIds.sort(Comparator.comparing(p -> p.toString().hashCode()));
                collect.sort(Comparator.comparing(p -> toString().hashCode()));
                if(orgProductIds.toString().equals(collect.toString())){
                    // 首先更新机构中所有产品的机构id为null
                    OrgProduct orgProduct = new OrgProduct();
                    orgProduct.setUpdateBy(createByName);
                    orgProduct.setOrgId(null);
                    // 库中机构产品关联的机构id更新为null
                    orgProductMapper.update(orgProduct,
                            new UpdateWrapper<OrgProduct>()
                                    .eq(OrgProduct.ORG_ID, insertOrgId));

                    // 批量更新org_product表中数据
                    for (Long orgProductId : orgProductIds) {
                        OrgProduct product = new OrgProduct();
                        product.setId(orgProductId);
                        product.setOrgId(insertOrgId);
                        product.setUpdateBy(createByName);
                        orgProductMapper.updateById(product);
                    }
                } else{
                    throw new ServiceException("传入的产品不存在");
                }
            } else{
                throw new ServiceException("传入的产品不存在");
            }
        }
        return org;
    }



    /**
     * 生成机构编码
     * @param orgType
     * @return
     */
    public String geneOrgCode(String orgType){
        String geneOrgCode = null;
        long initSeq = 1L;
        while (true) {
            String code  = geneOrgCode(orgType,initSeq);
            // 判断是否存在
            List<Org> orgs = orgMapper.selectList(
                    new QueryWrapper<Org>()
                            .eq(Org.ORG_CODE, code)
                            .eq(Org.DEL_FLAG, OrgConstants.DEL_FLAG_UNDELETED)
                            .orderByDesc(Org.ORG_CODE));
            if(orgs != null && orgs.size() > 0){
                String orgCode = orgs.get(0).getOrgCode();
                initSeq = Long.parseLong(orgCode.substring(2));
            }else{
                geneOrgCode  = code;
                break;
            }
        }
        return geneOrgCode;
    }

    /**
     * 生成机构编码
     * @param type
     * @return
     */
    private static String geneOrgCode(String type, Long initSeq){
        String orgCode = "";
        // 机构编码  -- 后台按照一定编码规则生成
        if (type.equals(SeqCodeUtils.OrgCodeSeqType.YH.type)) {
            orgCode = SeqCodeUtils.OrgCodeSeqType.YH.geneSeqCode(initSeq);
        }else if (type.equals(SeqCodeUtils.OrgCodeSeqType.BX.type)){
            orgCode = SeqCodeUtils.OrgCodeSeqType.BX.geneSeqCode(initSeq);
        }else if(type.equals(SeqCodeUtils.OrgCodeSeqType.DB.type)){
            orgCode = SeqCodeUtils.OrgCodeSeqType.DB.geneSeqCode(initSeq);
        }else if(type.equals(SeqCodeUtils.OrgCodeSeqType.QT.type)){
            orgCode = SeqCodeUtils.OrgCodeSeqType.QT.geneSeqCode(initSeq);
        }else{
            throw new ServiceException();
        }
        return orgCode;
    }
}
